#!/bin/bash

# 配置参数 - 请根据实际情况修改这些值
PACKAGE_NAME="my-awesome-cli-tools"
VERSION="1.0.0"
ARCHITECTURE="amd64"
MAINTAINER="Your Name <your@email.com>"
DESCRIPTION="一个用Go编写的很棒的CLI工具"
BINARY_PATH="./goscrot"  # 你的Go程序二进制文件路径
INSTALL_PATH="/usr/local/bin"  # 程序安装路径

# 检查二进制文件是否存在
if [ ! -f "$BINARY_PATH" ]; then
    echo "错误：未找到二进制文件 $BINARY_PATH"
    exit 1
fi

# 创建临时工作目录
WORK_DIR=$(mktemp -d)
echo "创建临时工作目录: $WORK_DIR"

# 创建Debian包目录结构
mkdir -p "$WORK_DIR/$PACKAGE_NAME/DEBIAN"
mkdir -p "$WORK_DIR/$PACKAGE_NAME/$INSTALL_PATH"

# 复制二进制文件
cp "$BINARY_PATH" "$WORK_DIR/$PACKAGE_NAME/$INSTALL_PATH/"

# 创建control文件
cat > "$WORK_DIR/$PACKAGE_NAME/DEBIAN/control" << EOF
Package: $PACKAGE_NAME
Version: $VERSION
Section: utils
Priority: optional
Architecture: $ARCHITECTURE
Depends: libc6 (>= 2.27)
Maintainer: $MAINTAINER
Description: $DESCRIPTION
 这是一个Go语言编写的CLI程序的Debian包。
EOF

# 创建postinst脚本（安装后执行）
cat > "$WORK_DIR/$PACKAGE_NAME/DEBIAN/postinst" << EOF
#!/bin/sh
chmod +x $INSTALL_PATH/$(basename $BINARY_PATH)
echo "$PACKAGE_NAME 已安装完成"
EOF

# 创建prerm脚本（卸载前执行）
cat > "$WORK_DIR/$PACKAGE_NAME/DEBIAN/prerm" << EOF
#!/bin/sh
rm -f $INSTALL_PATH/$(basename $BINARY_PATH)
echo "$PACKAGE_NAME 已卸载"
EOF

# 设置脚本执行权限
chmod +x "$WORK_DIR/$PACKAGE_NAME/DEBIAN/postinst"
chmod +x "$WORK_DIR/$PACKAGE_NAME/DEBIAN/prerm"

# 构建Debian包
dpkg-deb --build "$WORK_DIR/$PACKAGE_NAME"

# 移动生成的deb包到当前目录
mv "$WORK_DIR/$PACKAGE_NAME.deb" .

# 清理临时文件
rm -rf "$WORK_DIR"

echo "Debian包已生成: $(pwd)/$PACKAGE_NAME.deb"
echo "安装命令: sudo dpkg -i $PACKAGE_NAME.deb"
echo "卸载命令: sudo dpkg -r $PACKAGE_NAME"

